﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using HandyControl.Controls;
using Quicker.Public;
using Quicker.Public.Extensions;
using Quicker.Utilities._3rd;
using Window = System.Windows.Window;
using TextBox = System.Windows.Controls.TextBox;
using MessageBox = System.Windows.MessageBox;

namespace WpfApp1
{
    /// <summary>
    /// 自定义的ObservableDictionary类，用于通知前端进行数据更新，之所以使用修改为IDictionary而不是保留ObservableDictionary的名字是为了减少quicker的修改
    /// 参考：Johnny Li，帖子：https://www.cnblogs.com/lisweden/p/7009600.html
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class IDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged
    {
        public IDictionary()
            : base()
        { }

        private int _index;
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public event PropertyChangedEventHandler PropertyChanged;

        public new KeyCollection Keys
        {
            get { return base.Keys; }
        }

        public new ValueCollection Values
        {
            get { return base.Values; }
        }

        public new int Count
        {
            get { return base.Count; }
        }

        public new TValue this[TKey key]
        {
            get { return this.GetValue(key); }
            set { this.SetValue(key, value); }
        }

        public TValue this[int index]
        {
            get { return this.GetIndexValue(index); }
            set { this.SetIndexValue(index, value); }
        }

        public new void Add(TKey key, TValue value)
        {
            base.Add(key, value);
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, this.FindPair(key), _index));
            OnPropertyChanged("Keys");
            OnPropertyChanged("Values");
            OnPropertyChanged("Count");
        }

        public new void Clear()
        {
            base.Clear();
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            OnPropertyChanged("Keys");
            OnPropertyChanged("Values");
            OnPropertyChanged("Count");
        }

        public new bool Remove(TKey key)
        {
            var pair = this.FindPair(key);
            if (base.Remove(key))
            {
                this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, pair, _index));
                OnPropertyChanged("Keys");
                OnPropertyChanged("Values");
                OnPropertyChanged("Count");
                return true;
            }
            return false;
        }

        protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (this.CollectionChanged != null)
            {
                this.CollectionChanged(this, e);
            }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #region private方法
        private TValue GetIndexValue(int index)
        {
            for (int i = 0; i < this.Count; i++)
            {
                if (i == index)
                {
                    var pair = this.ElementAt(i);
                    return pair.Value;
                }
            }

            return default(TValue);
        }

        private void SetIndexValue(int index, TValue value)
        {
            try
            {
                var pair = this.ElementAtOrDefault(index);
                SetValue(pair.Key, value);
            }
            catch (Exception)
            {

            }
        }

        private TValue GetValue(TKey key)
        {
            if (base.ContainsKey(key))
            {
                return base[key];
            }
            else
            {
                return default(TValue);
            }
        }

        private void SetValue(TKey key, TValue value)
        {
            if (base.ContainsKey(key))
            {
                var pair = this.FindPair(key);
                int index = _index;
                base[key] = value;
                var newpair = this.FindPair(key);
                this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newpair, pair, index));
                OnPropertyChanged("Values");
                OnPropertyChanged("Item[]");
            }
            else
            {
                this.Add(key, value);
            }
        }

        private KeyValuePair<TKey, TValue> FindPair(TKey key)
        {
            _index = 0;
            try
            {
                foreach (var item in this)
                {
                    if (item.Key.Equals(key))
                    {
                        return item;
                    }
                    _index++;
                }
            }
            catch (Exception)
            {

            }

            return default(KeyValuePair<TKey, TValue>);
        }

        private int IndexOf(TKey key)
        {
            int index = 0;
            foreach (var item in this)
            {
                if (item.Key.Equals(key))
                {
                    return index;
                }
                index++;

            }
            return -1;
        }

        #endregion

    }

    /// <summary>
    /// 命令基类，如要使用command事件，则需要复制到quicker中
    /// </summary>
    public class BaseCommand : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            if (_execute != null && CanExecute(parameter))
            {
                _execute(parameter);
            }
        }

        private Func<object, bool> _canExecute;
        private Action<object> _execute;

        public BaseCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public BaseCommand(Action<object> execute) :
            this(execute, null)
        {
        }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = QuickerTest.dataContextX;
            this.Loaded += (s, e) =>
            {
                QuickerTest.OnWindowCreated(this, (IDictionary<string, object>)this.DataContext, null);
                QuickerTest.OnWindowLoaded(this, (IDictionary<string, object>)this.DataContext, null);
            };
        }
    }

    /// <summary>
    /// quicker需要使用的代码部分
    /// </summary>
    public static class QuickerTest
    {
        /// <summary>
        /// 绑定的数据映射，quciker业务代码不会使用这个变量，便于直接使用vs调试用，需要按照对应格式复制到quicker数据映射中，不要复制到“辅助C#代码”
        /// </summary>
        public static IDictionary<string, object> dataContextX = new IDictionary<string, object>(){
            {"hour","00" },
            {"minute","00" },
            {"second","00" },
            {"millisecond","00" },
            {"buttonPauseText", "开始" },
            {"viewBoxWidth", (double)800 },
            {"viewBoxHeight", (double)400 },
            {"message", "提示信息为空" },
            {"setSecond", 20 },
            {"messageVisibility","Collapsed" },//消息提示框显示状态，Visible显示、Hidden占位隐藏、Collapsed不占位隐藏
            {"textColor", "#FFFFFF" }
        };
        /// <summary>
        /// 这应该是一个bug，quicker这部分代码不能以#region开头，故开头定义了个这个占位
        /// </summary>
        const int a = 0;
        #region quicker事件，vs中无法调试，可选复制的代码，若不需要回调赋值，则可有可无，此处仅做备注记录
        //hour.change:compute=true
        //minute.change:compute=true
        //second.change:compute=true
        //setSecond.change:compute=true
        //textColor.change:compute=true
        #endregion
        
        #region quicker使用的代码部分（辅助C#代码），必须要复制的代码
        #region 事件触发代码
        
        /// <summary>
        /// 窗口创建后，代码待做方法提取分离
        /// </summary>
        /// <param name="win"></param>
        /// <param name="dataContext"></param>
        /// <param name="winContext"></param>
        public static void OnWindowCreated(Window win, IDictionary<string, object> dataContext, ICustomWindowContext winContext)
        {
            //MessageBox.Show("dataContext:" + dataContext.ToJson()); 
            #region 初始字段赋值
            defalutScreenWidth = SystemParameters.PrimaryScreenWidth;
            defalutScreenHeigth = SystemParameters.PrimaryScreenHeight;
            Hour = dataContext["hour"] == null ? 0 : Convert.ToInt32(dataContext["hour"]);
            Minute = dataContext["minute"] == null ? 0 : Convert.ToInt32(dataContext["minute"]);
            Second = dataContext["second"] == null ? 0 : Convert.ToInt32(dataContext["second"]);
            Millisecond = dataContext["millisecond"] == null ? 0 : Convert.ToInt32(dataContext["millisecond"]);
            defaultHour = Hour;
            defaultMinute = Minute;
            defaultSecond = Second;
            defaultMillisecond = Millisecond;

            setSecond = Convert.ToInt32(dataContext["setSecond"]);

            string textColor = dataContext["textColor"].ToString();
            SolidColorBrush brush = new SolidColorBrush
            {
                Color = StrColorToColor(textColor)
            };
            win.Foreground = brush;

            ((TextBlock)win.FindName("textColon")).FontSize = win.Height / 2;
            ((TextBlock)win.FindName("textMs")).FontSize = win.Height / 2;
            //窗口默认分辨率为800*400
            #endregion

            #region 线程处理
            //线程取消控制器
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken token = cancellationTokenSource.Token;
            //时分秒的线程
            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    if (pauseFlag == 0 && flag != 1 && flag != 3) continue;
                    if (flag == 1 && pauseFlag == 1)
                    {
                        SetTimeNow(dataContext);
                    }
                    else if (flag == 2 && pauseFlag == 1)
                    {
                        Second++;
                        SetTime(dataContext);
                    }
                    else if (flag == 3)
                    {
                        dataContext["millisecond"] = "00";
                        //计时结束
                        if (Second == 0 && Minute == 0 && Hour == 0)
                        {
                            if (isCountDownOver == false)
                            {
                                SetMessage(dataContext, "倒计时结束");
                                isCountDownOver = true;
                                MessageBox.Show("倒计时结束于：" + DateTime.Now);
                            }
                            continue;
                        }
                        //倒计时初始化
                        else if (pauseFlag == 0 && isCountDownInit == false)
                        {
                            SetMessage(dataContext, "当前模式设置为倒计时模式");
                            //setSecond = Convert.ToInt32(dataContext["setSecond"]);
                            //MessageBox.Show("当前setSecond为："+ setSecond);
                            GetTimeFromSecond();
                            SetTime(dataContext);
                            isCountDownInit = true;
                        }

                        if (!isCountDownOver && pauseFlag == 1)
                        {
                            Second--;
                            SetTime(dataContext);
                        }
                    }
                    Task.Delay(1000).Wait();
                }
            }, token);

            //由于毫秒级别的延时需要专用处理，这里使用多线程模拟，以减少资源调用
            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    if (pauseFlag!=1) continue;
                    if (flag == 1 && pauseFlag != 0)
                    {
                        dataContext["millisecond"] = (DateTime.Now.Millisecond / 10).ToString("00");
                    }
                    else if (flag == 2)
                    {
                        Millisecond++;
                        dataContext["millisecond"] = Millisecond.ToString("00");
                    }
                    else continue;
                    Task.Delay(10).Wait();
                }
            }, token);

            //由于wpf的特性，窗口关闭后不会自动回收线程，这里要手动停止线程
            win.Closing += (s, e) => {
                cancellationTokenSource.Cancel();
            };

            #endregion
        }
        /// <summary>
        /// 窗口加载后
        /// </summary>
        /// <param name="win"></param>
        /// <param name="dataContext"></param>
        /// <param name="winContext"></param>
        public static void OnWindowLoaded(Window win, IDictionary<string, object> dataContext, ICustomWindowContext winContext)
        {
            //MessageBox.Show("WinodwLoaded");
            #region 预定义窗口，并关联相关数据业务（时间有限，没做通用性适配）
            //一个秒的输入框
            Window secondWin = CreatSecondTextBoxWin(win, dataContext);
            //颜色选择框
            Window colorWin = CreatColorPickerWin(win, dataContext);

            #endregion
            #region 事件绑定
            //重置
            ((MenuItem)win.FindName("menuRes")).Click += (s, e) => { ResTime(dataContext); pauseFlag = 0; SetMessage(dataContext, "计时已重置"); dataContext["buttonPauseText"] = "开始"; };
            //关闭窗口菜单
            ((MenuItem)win.FindName("menuClose")).Click += (s, e) => { win.Close(); };
            //暂停菜单
            ((MenuItem)win.FindName("menuPause")).Click += (s, e) =>
            {
                if (pauseFlag == 0)
                {
                    pauseFlag = 1;
                    dataContext["buttonPauseText"] = "暂停";
                }
                else if (pauseFlag == 1)
                {
                    pauseFlag = 2;
                    dataContext["buttonPauseText"] = "恢复";
                }
                else if (pauseFlag == 2)
                {
                    pauseFlag = 1;
                    dataContext["buttonPauseText"] = "暂停";
                }
            };
            //消息栏菜单
            ((MenuItem)win.FindName("menuMessage")).Click += (s, e) =>
            {
                var tempVisibility = Convert.ToString(dataContext["messageVisibility"]);
                if (tempVisibility == "Collapsed" || tempVisibility == "Hidden")
                {
                    dataContext["messageVisibility"] = "Visible";
                    ((MenuItem)s).Header = "隐藏消息栏";
                }
                else
                {
                    dataContext["messageVisibility"] = "Collapsed";
                    ((MenuItem)s).Header = "显示消息栏";
                }
            };
            //时间显示模式
            ((MenuItem)win.FindName("menuMode1")).Click += (s, e) => { flag = 1; SetMessage(dataContext, "当前模式设置为时间显示模式"); };
            //正计时模式
            ((MenuItem)win.FindName("menuMode2")).Click += (s, e) =>
            {
                flag = 2;
                Second = 0;
                Minute = 0;
                Second = 0;
                Millisecond = 0;
                SetMessage(dataContext, "当前模式设置为正计时模式");
            };
            //倒计时模式，可使用command模式（已写示例）
            //倒计时模式
            ((MenuItem)win.FindName("menuMode3")).Click += (s, e) =>
            {
                if (!secondWin.IsActive)
                    secondWin.Show();
            };
            //颜色选择
            ((MenuItem)win.FindName("menuColor")).Click += (s, e) =>
            {
                if (!colorWin.IsActive)
                    colorWin.Show();
            };
            //鼠标拖动事件，拖动窗口
            ((StackPanel)win.FindName("stackPanel0")).MouseDown += (s, e) => { if (e.LeftButton == MouseButtonState.Pressed) win.DragMove(); };
            //滚轮滚动事件，缩放窗口，按下LeftCtrl时，每次缩放10像素，否者每次缩放桌面宽度的1/20
            ((StackPanel)win.FindName("stackPanel0")).MouseWheel += (s, e) =>
            {
                var tempStr = "";

                var baseWidth = Convert.ToDouble(dataContext["viewBoxWidth"]);
                var baseHeight = Convert.ToDouble(dataContext["viewBoxHeight"]);
                if (Keyboard.IsKeyDown(Key.LeftCtrl))
                {
                    baseWidth += e.Delta > 0 ? 10 : -10;
                    baseHeight += baseWidth / 2;
                }
                else
                {
                    baseWidth += e.Delta > 0 ? defalutScreenWidth / 20 : -defalutScreenWidth / 20;
                    baseHeight = baseWidth / 2;
                }
                win.Width = baseWidth;
                win.Height = baseHeight;
                dataContext["viewBoxWidth"] = baseWidth;
                dataContext["viewBoxHeight"] = baseHeight;
                ((TextBlock)win.FindName("textColon")).FontSize = win.Height / 2;
                ((TextBlock)win.FindName("textMs")).FontSize = win.Height / 2;
                SetMessage(dataContext, "窗口缩放，当前窗口宽高为：(" + baseWidth + "," + baseHeight + ")" + tempStr);
            };

            #endregion
        }
        /// <summary>
        /// 按钮点击后（功能单一，不推荐使用，各种控件的产生的事件均可在窗口加载中完成绑定，主要是此处的代码不方便vs调试用）
        /// </summary>
        /// <param name="controlName"></param>
        /// <param name="controlTag"></param>
        /// <param name="win"></param>
        /// <param name="dataContext"></param>
        /// <param name="winContext"></param>
        /// <returns></returns>
        public static bool OnButtonClicked(string controlName, object controlTag, Window win, IDictionary<string, object> dataContext, ICustomWindowContext winContext)
        {
            //if (controlName == "buttonPause")
            //{
            //    pauseFlag = !pauseFlag;
            //    if (dataContext["buttonPauseText"].ToString() == "开始") dataContext["buttonPauseText"] = "暂停";
            //    dataContext["buttonPauseText"] = pauseFlag ? "恢复" : "暂停";
            //    return true;
            //}
            //else if (controlName == "buttonRes")
            //{
            //    ResTime(dataContext);
            //    return true;
            //}
            return false;
        }
        #endregion

        #region 实体字段
        const int hourMax = 24;
        const int hourMin = 0;
        const int minuteMax = 60;
        const int minuteMin = 0;
        const int secondMax = 60;
        const int secondMin = 0;
        const int millisecondMax = 100;
        const int millisecondMin = 0;

        static int defaultHour = 0;
        static int defaultMinute = 0;
        static int defaultSecond = 0;
        static int defaultMillisecond = 0;

        static double defalutScreenWidth = 1920;
        static double defalutScreenHeigth = 1080;

        static bool isCountDownOver = false;
        static int setSecond = 10;
        static bool isCountDownInit = false;

        /// <summary>
        /// 1为正常显示时间，2为正计时，3为倒计时
        /// </summary>
        static int flag = 2;
        /// <summary>
        /// 暂停标识，0初始状态，1正常状态，2暂停状态 
        /// </summary>
        static int pauseFlag = 0;


        private static int hour;
        /// <summary>
        /// 时
        /// </summary>
        public static int Hour
        {
            get
            {
                return hour;
            }
            set
            {
                if (value < hourMin)
                {
                    hour = hourMax - 1;
                }
                else if (value >= hourMax)
                {
                    hour = hourMin;
                }
                else
                {
                    hour = value;
                }
            }
        }
        private static int minute;
        /// <summary>
        /// 分
        /// </summary>
        public static int Minute
        {
            get
            {
                return minute;
            }
            set
            {
                if (value < minuteMin)
                {
                    minute = minuteMax - 1;
                    Hour--;
                }
                else if (value >= minuteMax)
                {
                    minute = minuteMin;
                    Hour++;
                }
                else
                {
                    minute = value;
                }
            }
        }

        private static int second;
        /// <summary>
        /// 秒
        /// </summary>
        public static int Second
        {
            get
            {
                return second;
            }
            set
            {
                if (value < secondMin)
                {
                    Second = secondMax - 1;
                    Minute--;
                }
                else if (value >= secondMax)
                {
                    Second = secondMin;
                    Minute++;
                }
                else
                {
                    second = value;
                }
            }
        }

        private static int millisecond;
        /// <summary>
        /// 毫秒，毫秒级别的延时有较大误差，这里不计入秒的运算
        /// </summary>
        public static int Millisecond
        {
            get
            {
                return millisecond;
            }
            set
            {
                if (value < millisecondMin)
                {
                    Millisecond = millisecondMax - 1;
                    //Second--;
                }
                else if (value >= millisecondMax)
                {
                    Millisecond = millisecondMin;
                    //Second++;
                }
                else
                {
                    millisecond = value;
                }
            }
        }
        #endregion

        #region command事件示例，由于Template中的数据不容易通过name获取，因此其事件绑定可以由command来实现，虽说是绕弯了，但还是不想使用“OnButtonClicked”……如需使用，需要继承ICommand实现BaseCommand，将实体绑定到dataContext字典
        //private static BaseCommand buttonCommand;
        ///// <summary>
        ///// 按钮点击
        ///// </summary>
        //public static BaseCommand ButtonCommand
        //{
        //    get
        //    {
        //        if (buttonCommand == null)
        //        {
        //            buttonCommand = new BaseCommand(new Action<object>(o =>
        //            {
        //                GetTimeFromSecond();
        //                isCountDownOver = false;
        //                flag = 3;
        //                //MessageBox.Show("调用："+o.ToJson());
        //            }));
        //        }
        //        return buttonCommand;
        //    }
        //}
        #endregion

        #region 私有方法
        /// <summary>
        /// 重置时间为默认值，倒计时无效
        /// </summary>
        /// <param name="dataContext"></param>
        private static void ResTime(IDictionary<string, object> dataContext)
        {
            Hour = defaultHour;
            Minute = defaultMinute;
            Second = defaultSecond;
            Millisecond = defaultMillisecond;
            SetTime(dataContext);
            dataContext["millisecond"] = Millisecond.ToString("00");
        }
        /// <summary>
        /// 设置消息数据
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="message"></param>
        private static void SetMessage(IDictionary<string, object> dataContext, string message)
        {
            dataContext["message"] = "[" + DateTime.Now + "]" + message;
        }
        /// <summary>
        /// 设置时间
        /// </summary>
        /// <param name="dataContext"></param>
        private static void SetTime(IDictionary<string, object> dataContext)
        {
            dataContext["second"] = Second.ToString("00");
            dataContext["minute"] = Minute.ToString("00");
            dataContext["hour"] = Hour.ToString("00");
        }
        /// <summary>
        /// 时间设备当前时间
        /// </summary>
        /// <param name="dataContext"></param>
        private static void SetTimeNow(IDictionary<string, object> dataContext)
        {
            dataContext["hour"] = DateTime.Now.Hour.ToString("00");
            dataContext["minute"] = DateTime.Now.Minute.ToString("00");
            dataContext["second"] = DateTime.Now.Second.ToString("00");
        }
        /// <summary>
        /// 获取设置倒计时的时分秒
        /// </summary>
        private static void GetTimeFromSecond()
        {
            Second = setSecond % 60;
            Minute = setSecond < 60 ? 0 : setSecond / 60 % 60;
            Hour = setSecond < 3600 ? 0 : setSecond / 60 / 60 % 24;
        }
        /// <summary>
        /// 创建一个文本输入对话框，用于倒计时的参数输入
        /// </summary>
        /// <param name="win"></param>
        /// <returns></returns>
        private static Window CreatSecondTextBoxWin(Window win, IDictionary<string, object> dataContext)
        {
            Window tempWin = new Window
            {
                Title = "输入窗口",
                Width = 240,
                Height = 70,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Topmost = true,
                VerticalAlignment = VerticalAlignment.Center,
            };
            Label tempLable = new Label
            {
                Name = "tempLable",
                Content = "秒数：",
                Background = Brushes.Transparent,
                BorderThickness = new Thickness(0)
            };
            TextBox tempTextBox = new TextBox
            {
                Name = "tempTextBox",
                Width = 100,
                VerticalContentAlignment = VerticalAlignment.Center,
            };
            Button tempBotton = new Button
            {
                Name = "tempButton",
                Content = "确认"
            };
            StackPanel tempPanel = new StackPanel
            {
                Name = "tempGrid",
                VerticalAlignment = VerticalAlignment.Center,
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center,
            };
            tempPanel.Children.Add(tempLable);
            tempPanel.Children.Add(tempTextBox);
            tempPanel.Children.Add(tempBotton);
            tempWin.Content = tempPanel;

            tempBotton.Click += (s, e) =>
            {
                int second = 0;

                try
                {
                    second = Convert.ToInt32(tempTextBox.Text);
                    dataContext["setSecond"] = tempTextBox.Text;
                    setSecond = second;
                    GetTimeFromSecond();
                    isCountDownOver = false;
                    flag = 3;
                    tempWin.Hide();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("数字格式错误，请检查：" + ex.Message);
                    //throw;
                }

            };

            tempWin.Closing += (s, e) =>
            {
                var ps = PresentationSource.FromVisual(win);
                if (ps != null && !ps.IsDisposed)
                {
                    e.Cancel = true;
                    tempWin.Hide();
                }
            };

            win.Closed += (s, e) =>
            {
                tempWin.Close();
            };

            return tempWin;
        }
        /// <summary>
        /// 创建一个颜色输入框，用于改变文字颜色
        /// </summary>
        /// <param name="win"></param>
        /// <returns></returns>
        private static Window CreatColorPickerWin(Window win, IDictionary<string, object> dataContext)
        {
            Window tempWin = new Window
            {
                Title = "Default",
                Width = 245,
                Height = 390,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Topmost = true,
            };

            ColorPicker colorPicker = new ColorPicker
            {
                Name = "colorPicker",
            };

            StackPanel panel = new StackPanel
            {
                Orientation = Orientation.Vertical,
            };

            colorPicker.Canceled += (s, e) =>
            {
                tempWin.Hide();
            };

            colorPicker.Confirmed += (s, e) =>
            {
                dataContext["textColor"] = e.Info.ToString();
                win.Foreground = new SolidColorBrush(e.Info);
                tempWin.Hide();
            };

            //panel.Children.Add(label);
            panel.Children.Add(colorPicker);
            tempWin.Content = panel;

            tempWin.Closing += (s, e) =>
            {
                var ps = PresentationSource.FromVisual(win);
                if (ps != null && !ps.IsDisposed)
                {
                    e.Cancel = true;
                    tempWin.Hide();
                }
            };

            win.Closed += (s, e) =>
            {
                tempWin.Close();
            };

            return tempWin;
        }
        /// <summary>
        /// 颜色转换
        /// </summary>
        /// <param name="argbColor"></param>
        /// <returns></returns>
        private static Color StrColorToColor(string argbColor)
        {
            var o = ColorConverter.ConvertFromString(argbColor);
            if (o == null) return Color.FromArgb(255, 255, 255, 255);
            else return (Color)ColorConverter.ConvertFromString(argbColor);
        }
        #endregion
        #endregion
    }
}
